package com.yuyou.weixin.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yuyou.weixin.bean.ResBoolSimpleInfo;
import com.yuyou.weixin.bean.ReturnResult;
import com.yuyou.weixin.entity.SrsUser;
import com.yuyou.weixin.service.ISmsService;
import com.yuyou.weixin.service.ISrsActivityService;
import com.yuyou.weixin.service.ISrsUserService;
import com.yuyou.weixin.util.ImgUtils;
import com.yuyou.weixin.vo.req.ReqAddPrize;
import com.yuyou.weixin.vo.req.ReqCloseActivity;
import com.yuyou.weixin.vo.resp.RespActivityHome;
/**
 * @author ZY
 *
 */
@Api(value="ActivityController",description="活动操作接口")
@Validated
@RestController
@RequestMapping(value="/api/activity")
public class ActivityController {

	@Autowired
	private ISrsActivityService srsActivityService;

	@Autowired
	private ISmsService smsService;
	
	@Autowired
	private ISrsUserService srsUserService;
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());  
	
	@ApiOperation(value="落地页")
    @ApiImplicitParams({  	
    	@ApiImplicitParam(name = "projectCode", value = "projectCode", paramType="query", required = true),
        @ApiImplicitParam(name = "openId", value = "openId", paramType="query", required = true),
        @ApiImplicitParam(name = "srsActivityId", value = "活动id", paramType="query", required = true),
        @ApiImplicitParam(name = "headImg", value = "头像URL", paramType="query", required = false),
        @ApiImplicitParam(name = "name", value = "名字", paramType="query", required = false)
    })
    @RequestMapping(value ="/home",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult<RespActivityHome> home(
    		@NotBlank (message="openId不能为空") String openId,
    		@NotNull (message="srsActivityId不能为空") Long srsActivityId,   		
    		@NotBlank (message="projectCode不能为空") String projectCode,
    		String headImg,
    		String name
    		){
		
		String d_headImg=null;
    	String d_name =null;    	
		try {
			if(!StringUtils.isEmpty(headImg)){
				d_headImg = URLDecoder.decode(headImg, "UTF-8");
			}
			if(!StringUtils.isEmpty(name)){
				d_name = URLDecoder.decode(name, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("解码失败：",e);;
		}
		
		RespActivityHome res=srsActivityService.home(srsActivityId,openId,d_headImg,d_name,projectCode);		
    	return ReturnResult.success(res);
    }	
	
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "projectCode", value = "projectCode", paramType="query", required = true),
        @ApiImplicitParam(name = "openId", value = "openId", paramType="query", required = true),
        @ApiImplicitParam(name = "headImg", value = "头像URL", paramType="query", required = false),
        @ApiImplicitParam(name = "name", value = "名字", paramType="query", required = false)
    })
    @ApiOperation(value="我的活动,生成海报")
    @RequestMapping(value ="/myActivity",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult<Long> center(
    		@NotBlank (message="openId不能为空")  String openId,
    		@NotBlank (message="projectCode不能为空") String projectCode,
    		String headImg,String name){
    	
		String d_headImg=null;
    	String d_name =null; 	
		try {
			if(!StringUtils.isEmpty(headImg)){
				d_headImg = URLDecoder.decode(headImg, "UTF-8");
			}
			if(!StringUtils.isEmpty(name)){
				d_name = URLDecoder.decode(name, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("解码失败：",e);;
		}
    	
    	Long res=srsActivityService.myActivity(openId,d_headImg,d_name,projectCode);		
    	return ReturnResult.success(res);
    }


    @ApiOperation(value="保存获奖信息")
    @RequestMapping(value ="/prize",method = {RequestMethod.POST})
    public ReturnResult<Void> prize(@Validated @ModelAttribute ReqAddPrize reqAddPrize) throws Exception{
        //验证短信校验码
		ResBoolSimpleInfo<String> res = smsService.validate(reqAddPrize.getPhone(),"01", reqAddPrize.getCode());
        if(res.isSuccess()){
            boolean result = srsActivityService.prize(reqAddPrize);
            if(!result){return ReturnResult.fail("保存信息失败，请重试");}
        }else{
            return ReturnResult.fail(res.getMessage());
        }
        return ReturnResult.success("ok");
    }
    
    @ApiOperation(value="结束活动，生成二维码")
    @RequestMapping(value ="/closeActivity",method = {RequestMethod.POST})
    public ReturnResult<Void> closeActivity(@Validated @ModelAttribute ReqCloseActivity ReqCloseActivity) throws Exception{
    	
    	boolean result = srsActivityService.closeActivity(ReqCloseActivity);
    	if(!result){return ReturnResult.fail("结束活动失败，请重试");}
    	
        return ReturnResult.success("ok");
    }
    
    

    @ApiOperation(value="获取用户的头像")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "projectCode", value = "projectCode", paramType="query", required = true),
    	@ApiImplicitParam(name = "projectCode", value = "projectCode", paramType="query", required = true),
        @ApiImplicitParam(name = "openId", value = "openId", paramType="query", required = true)
    })
    @RequestMapping(value ="/img",method = {RequestMethod.GET, RequestMethod.POST})
    public void img(@NotBlank (message="openId不能为空")  String openId,@NotBlank (message="projectCode不能为空") String projectCode, HttpServletResponse response) throws Exception {
        String format = "png";
    	SrsUser srsUser=srsUserService.selectByOpenId(openId,projectCode);
    	if(srsUser==null || StringUtils.isEmpty(srsUser.getHeadImg())){
    		return;
    	}
    	InputStream imgStream=new ImgUtils().getImageStream(srsUser.getHeadImg()); 
    	if(imgStream==null){
    		return;
    	}
        BufferedImage image =  ImageIO.read(imgStream);
        ImageIO.write(image,format, response.getOutputStream());
    }
    

	
}
